package com.heima.article.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 拦截用户信息，获取用户id
 *
 * @author ybw
 * @version 1.0
 * @date 2021/12/13 14:27
 */
@Slf4j
public class ApUserTokenInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    // 获取请求头中的用户id
    String userId = request.getHeader("userId");
    Optional<String> optional = Optional.ofNullable(userId);
    if (optional.isPresent()) {
      // 将用户id存入ThreadLocal中
      ApUser apUser = new ApUser();
      apUser.setId(Integer.valueOf(userId));
      ApThreadLocalUtil.setUser(apUser);
    }
    return true;
  }

  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {
    ApThreadLocalUtil.clear();
  }
}
